package org.easy.mongo;

import com.alibaba.fastjson.JSON;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: Li chaojie
 * @Date: 2022/10/26
 * @Description:
 */
public class MongoUtil {

    private final MongoTemplate mongoTemplate;

    public MongoUtil(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    public <T> void insert(T entity, Class<T> entityClass) {
        mongoTemplate.insert(entity, entityClass.getSimpleName().toLowerCase());
    }

    public void insertOne(String collection, Document document) {
        mongoTemplate.getCollection(collection).insertOne(document);
    }

    public void insertMany(String collection, List<Document> documentList) {
        mongoTemplate.getCollection(collection).insertMany(documentList);
    }


    public <T> T findById(String id, Class<T> entityClass) {
        return mongoTemplate.findById(id, entityClass);
    }


    public <T> List<T> findAll(Class<T> entityClass) {
        return mongoTemplate.findAll(entityClass);
    }


    public <T> void deleteById(String id, Class<T> entityClass) {
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query, entityClass);
    }


    private <T> T copy(Object source, Class<T> target) {

        if (source == null || target == null) {
            return null;
        }
        return JSON.parseObject(JSON.toJSONString(source), target);
    }

    private <T, E> List<T> copyList(List<E> source, Class<T> target) {
        if (source == null || target == null) {
            return new ArrayList<>();
        }

        return source.stream().map(e -> this.copy(e, target)).collect(Collectors.toList());
    }
}
